const { truncate } = require('fs/promises')

const MongoClient = require('mongodb').MongoClient

class Dao {
    constructor(url, dbName, collectionName) {
        this.url = url
        this.dbName = dbName
        this.collectionName = collectionName
    }
    _connect() {
        return new Promise((resolve, reject) => {
            MongoClient.connect(this.url, {
                useNewUrlParser: true,
                useUnifiedTopology: true
            }, (err, client) => {
                if (err) return reject(err)
                resolve(client)
            })
        })
    }
    insert(obj, isMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                debugger
                if (isMany) {
                    let db = client.db(this.dbName)// 找表明插入数据
                    db.collection(this.collectionName).insertMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })

                } else {
                    let db = client.db(this.dbName)
                    db.collection(this.collectionName).insertOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    }) // 找表明插入数据

                }
            })
        })

    }
    delect(obj, isMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                debugger
                if (isMany) {
                    let db = client.db(this.dbName)// 找表明插入数据
                    db.collection(this.collectionName).deleteMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })

                } else {
                    let db = client.db(this.dbName)
                    db.collection(this.collectionName).deleteOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    }) // 找表明插入数据

                }
            })
        })

    }
    update(filter, updater) {
        console.log("updater", updater)
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let uppdaterCpy = { $set: updater };
                let db = client.db(this.dbName);//连接数据库
                db.collection(this.collectionName).updateMany(filter, uppdaterCpy).then((res) => {
                    resolve(res)
                    client.close()
                })
            })
        })
    }
    /**
     * 查询
     * @param collection 集合名称
     * @param params 查询条件
     * @param cb
     */
    query(params) {
        params = params || {} // 查询条件
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName);//连接数据库
                db.collection(this.collectionName)
                    .find(params)
                    .toArray(function (err, results) {
                        resolve(results)
                        console.log(err, results)
                        client.close()
                    })

            })
        })
    }
    /**
     * 查询一条记录
     * @param collection 集合名称
     * @param params 查询条件
     * @param cb
     */
    queryone(params) {
        params = params || {} // 查询条件
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName);//连接数据库
                // let queryRes = db.collection(this.collectionName).find(obj)
                // console.log(queryRes)
                // console.log(queryRes.each((err,data)=>{console.log(data)}))
                db.collection(this.collectionName).findOne(params, function (err, results) {
                    // cb(err, results);
                    resolve(results)
                    client.close()
                });

            })
        })
    }
    /**
    * 查询所有数据(分页)
    * @param collection 集合名称
    * @param obj 查询参数
    * @param cb
    */
    queryAll(obj) {
        console.log("obj",obj,obj.params)
        obj.params = obj.params || {};
        obj.sortObj = obj.sortObj || {};
        obj.limit = obj.limit || 10;
        obj.page = obj.page || 0;
        obj.skip = obj.limit * obj.page;
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName);//连接数据库
                // let queryRes = db.collection(this.collectionName).find(obj)
                // console.log(queryRes)
                // console.log(queryRes.each((err,data)=>{console.log(data)}))
                db.collection(this.collectionName)
                .find(obj.params)
                .sort(obj.sortObj)
                .limit(obj.limit)
                .skip(obj.skip)
                .toArray(function (err, results) {
                    if(err){
                        reject(err)
                    }
                    resolve(results)
                });

            })
            
        })

    }
}
// url 数据库名称 表名
// const dao = new Dao("mongodb://localhost:27017", "test", "user")

// let obj =[]
// for(var i = 0;i<20;i++){
//     obj.push({
//         userId:"分页"+i,
//         age:20,
//     })
// }

// dao.insert(obj,true).then(() => {
//     console.log("插入成功")
// }).catch(()=>{
//     console.log("插入失败")
// })

// let obj = {userId:"妖怪"}
// dao.delect(obj).then((res)=>{
//     console.log(res)
// })

// let obj = {userId:'妖怪3'}
// let updater = {userId:'许仙'}

// dao.update(obj,updater).then(res=>{
//     console.log(res)
// })


// let obj = {userId:'妖怪1'}
// let obj1 = { userId: '许仙', age: '23' }

// dao.queryone(obj1).then(res => {
//     console.log(res)
// })

// let query = {params:{age:20},limit:5,page:2}

// dao.queryAll(query).then((res)=>{
//     console.log(res)
// })

module.exports = Dao